import io

from django.contrib.auth.models import User
from django.http import HttpResponse
from django.views import View
from django_redis import get_redis_connection
from rest_framework.mixins import UpdateModelMixin
from rest_framework.permissions import IsAuthenticated
from rest_framework.viewsets import GenericViewSet

from users.serializers import UserSerializer
from utils.verify import ImageVerify


class VerifyCodeViewSet(View):
    def get(self, request, uuid):
        imageVerify = ImageVerify()
        image, code = imageVerify.verify_code()
        image_bytes = io.BytesIO()
        image.save(fp=image_bytes, format='PNG')
        image_bytes = image_bytes.getvalue()
        # 将客户端标识 uuid 作为key，验证码 结果为key存入 redis中
        cache = get_redis_connection(alias='verify_code')  # 从redis 中拿取 一个链接对象
        cache.set("login:verification:%s" % uuid, code, 60 * 3)
        return HttpResponse(image_bytes, content_type='image/png')


class UserViewSet(GenericViewSet, UpdateModelMixin):
    queryset = User.objects.all()
    serializer_class = UserSerializer
    permission_classes = [IsAuthenticated]